class MultiSerialPort {
public:
    using ReceiveCallback = std::function<void(int portIndex, const char* data, int length)>;
    using StatusCallback = std::function<void(int portIndex, bool isConnected)>;
    using TaskCallback = std::function<void(int portIndex, const std::string& portName)>; // 任务回调

    bool openPort(int portIndex, const std::string& portName, int baudRate);
    void closePort(int portIndex);
    void closeAllPorts();
    bool sendData(int portIndex, const char* data, int length);
    // ... 其他成员函数和变量 ...

    void autoConnectUART(int baudRate, TaskCallback task); // 新增 task 参数

private:
    std::set<std::string> connectedPortNames; // 存储已连接的串口名称，确保唯一性
    std::queue<std::string> availablePorts;  // 存储待连接的串口名称
    std::mutex queueMutex;                   // 保护任务队列的互斥锁
    std::atomic<bool> running{false};        // 控制任务线程的运行状态

    void processTasks(int baudRate, TaskCallback task); // 处理任务的函数
};

void MultiSerialPort::autoConnectUART(int baudRate, TaskCallback task) {
    // 获取所有可用的串口信息
    std::vector<itas109::SerialPortInfo> portList = itas109::CSerialPortInfo::availablePortInfos();

    // 将所有可用的串口名称加入队列
    {
        std::lock_guard<std::mutex> lock(queueMutex);
        for (const auto& portInfo : portList) {
            if (connectedPortNames.find(portInfo.portName) == connectedPortNames.end()) {
                availablePorts.push(portInfo.portName);
            }
        }
    }

    // 启动任务处理线程
    running = true;
    std::thread taskThread(&MultiSerialPort::processTasks, this, baudRate, task);
    taskThread.detach(); // 分离线程，让它在后台运行
}

void MultiSerialPort::processTasks(int baudRate, TaskCallback task) {
    while (running) {
        std::string portName;
        {
            std::lock_guard<std::mutex> lock(queueMutex);
            if (availablePorts.empty()) {
                // 没有可用的串口，等待一段时间后重试
                std::this_thread::sleep_for(std::chrono::seconds(1));
                continue;
            }
            portName = availablePorts.front();
            availablePorts.pop();
        }

        // 尝试连接串口
        int portIndex = -1;
        for (int i = 0; i < maxPorts; ++i) {
            if (!portStatus[i]) {
                portIndex = i;
                break;
            }
        }

        if (portIndex == -1) {
            // 没有可用的端口索引，等待一段时间后重试
            std::this_thread::sleep_for(std::chrono::seconds(1));
            continue;
        }

        if (this->openPort(portIndex, portName, baudRate)) {
            // 发送 AT 命令并检查响应
            const char* atCommand = "AT\r\n";
            this->sendData(portIndex, atCommand, strlen(atCommand));

            char buffer[32] = {0};
            int bytesRead = this->serialPorts[portIndex].readData(buffer, sizeof(buffer) - 1);
            if (bytesRead > 0 && std::string(buffer).find("OK") != std::string::npos) {
                // 连接成功
                USER_PRINTF_LOG(LOG_FILE, "Connected to %s (channel: %d)", portName.c_str(), portIndex);

                // 添加到已连接集合
                connectedPortNames.insert(portName);

                // 调用任务回调函数
                if (task) {
                    task(portIndex, portName);
                }

                // 任务完成后关闭串口
                this->closePort(portIndex);
                USER_PRINTF_LOG(LOG_FILE, "Closed port %s (channel: %d)", portName.c_str(), portIndex);

                // 从已连接集合中移除
                connectedPortNames.erase(portName);
            } else {
                // 连接失败，关闭串口
                this->closePort(portIndex);
                USER_PRINTF_LOG(LOG_FILE, "Failed to connect to %s", portName.c_str());
            }
        }
    }
}